package com.the_ring.chapter12.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 使用
 * Movie movie = Movie.decodeStream(getResources().openRawSource(imageId));
 * gifGv.setMovie(movie);
 */
public class GifView extends View {

    private Movie movie;            // 声明电影对象
    private long beginTime = 0;     // 开始播放时间
    private float scaleRatio = 1;   // 缩放比率

    public GifView(Context context) {
        this(context, null);
    }

    public GifView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    // 设置电影对象
    public void setMovie(Movie movie) {
        this.movie = movie;
        requestLayout();    // 请求重新调整视图位置
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (movie != null) {
            int width = movie.width();
            int height = movie.height();
            float widthRatio = 1.0f * getMeasuredWidth() / width;
            float heightRatio = 1.0f * getMeasuredHeight() / height;
            scaleRatio = Math.min(widthRatio, heightRatio);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        long now = SystemClock.uptimeMillis();
        if (beginTime == 0) {       // 如果是第一帧，就记录起始时间
            beginTime = now;
        }
        if (movie != null) {
            // 获取电影动图的播放时长
            int duration = movie.duration() == 0 ? 1000 : movie.duration();
            // 计算当前显示第几帧图片
            int currentTime = (int) ((now - beginTime) % duration);
            movie.setTime(currentTime);             // 设置当前帧的相对时间
            canvas.scale(scaleRatio, scaleRatio);   // 将画布缩放到指定比率
            movie.draw(canvas, 0, 0);           // 将当前帧绘制到画布上
            postInvalidate();                       // 立即刷新视图
        }
    }
}
